package com.zhw.aop;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import com.zhw.Util.JwtUtils;
import com.zhw.mapper.OperateLogMapper;
import com.zhw.pojo.OperateLog;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

@Component
@Slf4j
@Aspect
public class LogAspect {

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private OperateLogMapper operateLogMapper;


    @Around("@annotation(com.zhw.anno.Log)")
    public Object operateLog(ProceedingJoinPoint pjp) throws Throwable {
        //获取操作人员id
        //每次请求都需要携带令牌，令牌内有登录的信息
        String token = request.getHeader("token");
        Claims claims = JwtUtils.parseJWT(token);

        Integer id = (Integer) claims.get("id");



        //获取操作时间operateTime
        LocalDateTime operateTime = LocalDateTime.now();


        //获取操作类名className
        String className = pjp.getTarget().getClass().getName();


        //获取操作方法名methodName
        String methodName = pjp.getSignature().getName();


        //获取操作参数methodParams
        Object[] args = pjp.getArgs();
        String methodParams = Arrays.toString(args);


        //获取返回值returnValue
        long begin = System.currentTimeMillis();
        Object result = pjp.proceed();

        String returnValue = JSONObject.toJSONString(result);
        long end = System.currentTimeMillis();


        //获取操作耗时costTime
        long costTime=end-begin;


        OperateLog Log=new OperateLog(null,id,operateTime,className,methodName,methodParams,returnValue,costTime);
        operateLogMapper.insert(Log);
        return result;

    }


}
